﻿package emusic.api.adapters 
{
	import emusic.api.data.AlbumData;
	/**
	 * ...
	 * @author Martin Legris ( http://blog.martinlegris.com )
	 */
	public class AlbumAdapter
	{
		public static function digestAlbum(album:XML):AlbumData
		{
			var data:AlbumData = new AlbumData();
			data.added = digestDate(album.@added);
			data.artist = SummaryAdapter.digestSummary(album.artist[0]);
			data.genre = SummaryAdapter.digestSummary(album.genre[0]);
			data.id = parseInt(album.@id);
			data.image = album.@image;
			data.label = SummaryAdapter.digestSummary(album.label[0]);
			data.name = album.@name;
			data.released = digestDate(album.@released);
			data.sample = album.@sample;
			data.siteUrl = album.@url;
			try { 
				data.communityRating = parseFloat(album.ratings[0].communityRating.@average.toString());
			} catch (e:TypeError) { data.communityRating = 0 };
			
			return data;
		}
		
		public static function digestDate(strDate:String):Date
		{
			if (strDate == "")
				return null;
				
			var exp:RegExp = /(\d\d\d\d)([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])/i;
			var res:Object = exp.exec(strDate);
			var time:Date = new Date(res[1], res[3] - 1, res[4] - 1);
			
			return time;
			
		}
	}
}